﻿using Infrastructure.Image;
using Infrastructure.Web;
using MyApplication;
using MyData.ApiDto;
using MyData.Dto;
using MyData.Models;
using MyWeb.App_Start;
using MyWeb.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Infrastructure.Json;
using System.Text;
using Infrastructure.FileOperate;

namespace MyWeb.Controllers.Api
{
    [RoutePrefix("api/mobile")]
    public class ApiMobileController : BaseApiController
    {
        /// <summary>
        /// App注册
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("MobileLogin")]
        // GET api/<controller>
        public AjaxResult<MobileLoginOput> MobileLogin([FromBody]MobileLoginInput input)
        {
            AjaxResult<MobileLoginOput> ajaxResult = new AjaxResult<MobileLoginOput>();
            return base.Try<MobileLoginOput>(() =>
            {
                ajaxResult.data = AutofacExt.GetFromFac<MobileApp>().MobileLogin(input);

            }, ajaxResult);
        }
        /// <summary>
        /// 同步用户信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("SynsUser")]
        public AjaxResult<SynsOput> SynsUser([FromBody]SynsInput synsInput)
        {
            AjaxResult<SynsOput> ajaxResult = new AjaxResult<SynsOput>();
            return base.Try<SynsOput>(() =>
            {
                ajaxResult.data = AutofacExt.GetFromFac<SynsRLApp>().GetSynsOput(synsInput.MobileId);

            }, ajaxResult);

        }
        /// <summary>
        /// 同步用户信息分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("SynsUserP")]
        public AjaxResult<SynsOput> SynsUser([FromBody]SynsInputP synsInput)
        {
            AjaxResult<SynsOput> ajaxResult = new AjaxResult<SynsOput>();
            return base.Try<SynsOput>(() =>
            {
                ajaxResult.data = AutofacExt.GetFromFac<SynsRLApp>().GetSynsOput(synsInput.MobileId, synsInput.PageIndex, synsInput.PageSize);

            }, ajaxResult);

        }
        /// <summary>
        /// 删除已同步用户信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("DeleteSynsUser")]
        public AjaxResult DeleteSynsUser([FromBody]SynsInput synsInput)
        {
            return base.Try(() =>
            {
                AutofacExt.GetFromFac<SynsRLApp>().DeleteSyns(synsInput.MobileId);

            });
        }
        /// <summary>
        /// 进出门记录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("SaveAccessRecord")]
        public AjaxResult<bool> SaveAccessRecord([FromBody]AccessRecordInput accessRecordInput)
        {
            AjaxResult<bool> ajaxResult = new AjaxResult<bool>();
            return base.Try(() =>
            {
                if (accessRecordInput.UserId != Guid.Empty)
                {
                    AccessRecord accessRecord = new AccessRecord()
                    {
                        Id = Guid.NewGuid(),
                        UserId = accessRecordInput.UserId,
                        MobileId = accessRecordInput.MobileId,
                        PicPath = "",
                        CreateDate = DateTime.Now.ToString("yyyy-MM-dd"),
                        Similar = accessRecordInput.Similar,
                        UserType = accessRecordInput.UserType,
                        TurnOver= accessRecordInput.TurnOver
                    };

                    if (!string.IsNullOrEmpty(accessRecordInput.PicPath))
                    {
                        Bitmap bitmap = ImageHelper.ConvertStringToBitmap("data:image/jpeg;base64," + accessRecordInput.PicPath);
                        string fullPath = AppDomain.CurrentDomain.BaseDirectory + imgPath;
                        if (!Directory.Exists(fullPath))
                        {
                            Directory.CreateDirectory(fullPath);
                        }
                        string fileName = Guid.NewGuid().ToString() + ".jpg";
                        bitmap.Save(fullPath + fileName);
                        accessRecord.PicPath = imgPath + fileName;
                    }
                    AutofacExt.GetFromFac<AccessRecordApp>().SaveAccessRecord(accessRecord);
                }

                var model = AutofacExt.GetFromFac<SynsRLApp>().GetSynsOput(accessRecordInput.MobileId);
                if (model.UserInfoSynsOputs.Count == 0 && model.DeleteUserIds.Count == 0 && model.VisitorSynsOputs.Count == 0 && model.DeleteVisitors.Count == 0)
                {
                    ajaxResult.data = false;
                }
                else
                {
                    ajaxResult.data = true;
                }

            }, ajaxResult);
        }
        /// <summary>
        /// 批量进出门记录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("SaveBatchAccessRecord")]
        public AjaxResult SaveBatchAccessRecord([FromBody]BatchAccessRecord accessRecordInput)
        {
            return base.Try(() =>
            {
                Bitmap bitmap = ImageHelper.ConvertStringToBitmap(accessRecordInput.Base64);
                string fullPath = AppDomain.CurrentDomain.BaseDirectory + imgPath;
                if (!Directory.Exists(fullPath))
                {
                    Directory.CreateDirectory(fullPath);
                }
                string fileName = Guid.NewGuid().ToString() + ".jpg";
                bitmap.Save(fullPath + fileName);
                List<AccessRecord> accessRecords = new List<AccessRecord>();
                foreach (var item in accessRecordInput.AccessRecords)
                {
                    accessRecords.Add(new AccessRecord() { Id = Guid.NewGuid(),TurnOver=accessRecordInput.TurnOver,UserType=item.UserType, UserId = item.UserId, MobileId = accessRecordInput.MobileId, PicPath = imgPath + fileName, CreateDate = DateTime.Now.ToString("yyyy-MM-dd"), Similar = item.Similar });
                }

                AutofacExt.GetFromFac<AccessRecordApp>().SaveAccessRecord(accessRecords);

            });
        }
        /// <summary>
        /// 同步会议用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("SynsMeetUser")]
        public AjaxResult<SynsMeetUser> SynsMeetUser([FromBody]SynsInput synsInput)
        {
            AjaxResult<SynsMeetUser> ajaxResult = new AjaxResult<SynsMeetUser>();
            return base.Try<SynsMeetUser>(() =>
            {
                SynsMeetUser dto = AutofacExt.GetFromFac<VisitorApp>().GetSynsMeetUser(synsInput.MobileId);
                ajaxResult.data = dto;
            }, ajaxResult);
        }
        /// <summary>
        /// 进出门记录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("SaveAccessRecordRM")]
        public RecordOput SaveAccessRecord([FromBody]RecordInput input)
        {

            RecordOput model = new RecordOput();
            try
            {

                if (Request.Headers.GetValues("Ver").FirstOrDefault() != null)
                {

                }
                if (Request.Headers.GetValues("Command").FirstOrDefault() != null)
                {

                }

                if (String.IsNullOrEmpty(input.userID))
                {
                    model.commandid = input.commandid;
                    model.msg = "userID不可为空";
                    model.errorcode = -1;
                }
                else
                {
                    MobileLoginInput mobile = new MobileLoginInput();
                    mobile.ImeiNum = input.machineCode;
                    MobileLoginOput mobileDB = AutofacExt.GetFromFac<MobileApp>().MobileLogin(mobile);
                    Guid userId = Guid.Parse(input.userID);
                    AccessRecord accessRecord = new AccessRecord() { Id = Guid.NewGuid(), UserId = userId, MobileId = mobileDB.Id, PicPath = input.photo, CreateDate = DateTime.Now.ToString("yyyy-MM-dd") };
                    AutofacExt.GetFromFac<AccessRecordApp>().SaveAccessRecord(accessRecord);



                    model.commandid = input.commandid;
                    model.msg = "";
                    model.errorcode = 0;
                }


            }
            catch (Exception ex)
            {
                model.commandid = input.commandid;
                model.msg = ex.Message;
                model.errorcode = -1;
            }
            return model;
        }
        /// <summary>
        /// 检索最新记录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetRecentRecord")]
        public RecentRecordDto GetRecentRecord()
        {
            return AutofacExt.GetFromFac<AccessRecordApp>().GetRencentReord();
        }
        /// <summary>
        /// 检索最新记录8
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetRecentRecord8")]
        public AjaxResult<List<RecentRecordDto>> GetRecentRecord8([FromBody]SynsInput input)
        {
            AjaxResult<List<RecentRecordDto>> ajaxResult = new AjaxResult<List<RecentRecordDto>>();
            return base.Try(() =>
            {
                ajaxResult.data = AutofacExt.GetFromFac<AccessRecordApp>().GetRencentRecord8(input.MobileId);
            }, ajaxResult);
        }
        private static string imgPath = @"/Attach/Record/";
        /// <summary>
        /// 检索最新记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SaveRecordPic")]
        public AjaxResult SaveRecordPic([FromBody]SaveRecordPicModel input)
        {
            return base.Try(() =>
            {
                Bitmap bitmap = ImageHelper.ConvertStringToBitmap(input.Base64);
                string fullPath = AppDomain.CurrentDomain.BaseDirectory + imgPath;
                if (!Directory.Exists(fullPath))
                {
                    Directory.CreateDirectory(fullPath);
                }
                string fileName = input.RecordId.ToString() + ".jpg";
                bitmap.Save(fullPath + fileName);
                AutofacExt.GetFromFac<AccessRecordApp>().SaveRecordPic(input.RecordId, imgPath + fileName);
            });
        }
        /// <summary>
        ///保存错误日志
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SaveSyncError")]
        public AjaxResult SaveSyncError([FromBody]SaveSyncErrorInput input)
        {
            return base.Try(() =>
            {
                SyncError syncError = new SyncError();
                syncError.ErrorMessage = input.ErrorMessage;
                syncError.ErrorType = input.ErrorType;
                syncError.MobileId = input.MobileId;
                syncError.OperateType = input.OperateType;
                syncError.UserId = input.UserId;
                syncError.UserType = input.UserType;
                AutofacExt.GetFromFac<SyncErrorApp>().SaveSyncError(syncError);
            });
        }

    }

}